/*
 * Copyright (C) 2022-2022. Huawei Technologies Co., Ltd. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.openlookeng.handler;

import com.baomidou.mybatisplus.extension.api.R;
import com.openlookeng.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler
{
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public R<T> MyExceptionHandle(MethodArgumentNotValidException exception)
    {
        exception.printStackTrace();
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(error -> {
                System.out.println("field" + error.getField() + ", msg:" + error.getDefaultMessage());
                errorMsg.append(error.getDefaultMessage()).append("!");
            });
        }
        exception.printStackTrace();
        return R.failed(errorMsg.toString());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R<T> error(Exception e)
    {
        return R.failed("系统异常:" + e.getMessage());
    }

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public R<T> error(BizException e)
    {
        return R.failed(e.getInfo());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public R<T> error(ConstraintViolationException e)
    {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> msg = new ArrayList<>();
        constraintViolations.forEach(item -> msg.add(item.getMessage()));
        return R.failed(String.join(";", msg));
    }
}
